package com.itheima.aop;
import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.DeptLogMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.DeptLog;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Enumeration;

@Component
@Aspect
@RequiredArgsConstructor
public class LogAspect {

    private final JwtUtils jwtUtils;
    private final OperateLogMapper deptLogMapper;
    private final HttpServletRequest request;

    @Around("@annotation(com.itheima.annotation.Log)")
    public Object recording(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String token = request.getHeader("token");
        Claims claims = jwtUtils.parseJWT(token);

        OperateLog operateLog = new OperateLog();
        // 获取当前登录用户的id
        operateLog.setOperateUser((Integer) claims.get("id"));
        // 获取当前时间
        operateLog.setOperateTime(LocalDateTime.now());
        // 获取类名称
        operateLog.setClassName(proceedingJoinPoint.getTarget().getClass().getName());
        // 获取方法名称
        operateLog.setMethodName(proceedingJoinPoint.getSignature().getName());
        // 获取方法参数
        operateLog.setMethodParams(proceedingJoinPoint.getArgs().toString());
        // 获取方法开始时间
        long begin = System.currentTimeMillis();
        // 执行方法
        Object result = proceedingJoinPoint.proceed();
        // 获取方法结束时间
        long end = System.currentTimeMillis();
        // 获取方法执行时间
        operateLog.setCostTime(end - begin);
        // 获取方法返回值
        operateLog.setReturnValue(JSONObject.toJSONString(result));


        deptLogMapper.insert(operateLog);
        return result;
    }
}
